import {request} from "../../utils/util";
let app = getApp()

Page({
  data: {
    swiperIdx: 0,
    discount: false,
    showSelPay: false,
    details: {},
    addressList: [],
    currentAddr: {}, // 当前选中地址
    payForm: {
      order_sn: '',
      pay_money: '',
    },
    submitForm: {
      goods_id: '',
      venue_id: '',
      num: 1,
      amount: '', // 总金额
      pickup_type: '1', // 1：自提，2：快递
      consignee_id: 0, // 收货地址id
      actual_payment: '', // 实付金额
      points_deduction: '', // 积分抵扣
    },
    pointDeduction: 0, // 积分可抵扣金额
    deductPoint: 0, // 需要花费的积分
  },
  // 计算积分可抵扣的金额，以及需要花费的积分
  calcPointDeduction() {
    let { price, express, pointToBalance, user_point } = this.data.details
    let { amount, num, pickup_type } = this.data.submitForm
    let pointDeduction = (pointToBalance * user_point).toFixed(2)
    let deductPoint = user_point
    amount = price * num
    if (pickup_type === '2') {
      amount += express
    }
    if (pointDeduction*1 > amount*1) {
      pointDeduction = amount
      // 积分太多，抵扣金额大于支付金额时，需重新计算实际花费的积分，向上取整
      deductPoint = Math.ceil(amount / pointToBalance)
    }
    this.setData({
      pointDeduction,
      deductPoint,
      submitForm: {
        ...this.data.submitForm,
        amount
      }
    })
    this.calcShowMoney()
  },
  calcShowMoney() {
    if (this.data.discount) {
      this.setData({
        submitForm: {
          ...this.data.submitForm,
          actual_payment: (this.data.submitForm.amount - this.data.pointDeduction).toFixed(2),
          points_deduction: this.data.pointDeduction
        },
      })
    } else {
      this.setData({
        submitForm: {
          ...this.data.submitForm,
          actual_payment: this.data.submitForm.amount,
          points_deduction: 0
        },
      })
    }
  },
  selWay (e) {
    let { type } = e.currentTarget.dataset
    let consignee_id = 0
    let currentAddr = {}
    if (type === '2' && this.data.addressList.length) {
      this.data.addressList.forEach(item => {
        if (item.is_default === 0) {
          consignee_id = item.id
          currentAddr = item
        }
      })
    } else if (type === '1') {
      consignee_id = 0
    }
    this.setData({
      submitForm: {
        ...this.data.submitForm,
        pickup_type: type,
        consignee_id
      },
      currentAddr
    })
    this.calcPointDeduction()
  },
  plusNum () {
    let { details, submitForm } = this.data;
    let num = submitForm.num
    num++
    if (num > details.num) {
      wx.showToast({
        title: '库存不足',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    this.setData({
      submitForm: {
        ...submitForm,
        num
      }
    })
    this.calcPointDeduction()
  },
  reduceNum () {
    let { submitForm } = this.data;
    submitForm.num--
    if (submitForm.num <=1 ) submitForm.num = 1
    this.setData({
      num: submitForm.num
    })
    this.calcPointDeduction()
  },
  discountChange () {
    if (this.data.details.user_point <= 0) {
      return false
    }
    this.setData({
      discount: !this.data.discount
    })
    this.calcPointDeduction()
  },
  toAddress (e) {
    let { type } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/address/index?type=choose`
    })
  },
  toPay () {
    if (this.data.submitForm.pickup_type === '2' && this.data.submitForm.consignee_id === 0) {
      wx.showToast({
        title: '收获地址不能为空',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    this.setData({
      submitForm: {
        ...this.data.submitForm,
        goods_id: this.options.goods_id,
        venue_id: this.options.venue_id
      }
    })
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/shop/orders`,
      method: 'POST',
      data: this.data.submitForm,
      success: ({ code, data, message }) => {
        wx.hideLoading()
        if (code === 200) {
          this.setData({
            payForm: {
              order_sn: data.order_sn,
              pay_money: this.data.submitForm.actual_payment,
            },
            showSelPay: true
          })
          this.calcPointDeduction()
        } else if (code === 201) {
          wx.showToast({
            title: '支付成功！',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/goodsOrder/index'
            })
          }, 1000)
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  closePay() {
    this.setData({
      showSelPay: false
    })
  },
  // 获取详情数据
  getDetails() {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/shop/detail/${this.options.goods_id}`,
      success: ({ code, data, message }) => {
        wx.hideLoading()
        if (code === 200) {
          this.setData({
            details: data
          }, () => {
            this.calcPointDeduction()
          })
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 获取地址列表
  getAddress() {
    request({
      url: '/api/web/consignees',
      success: ({ code, data }) => {
        if (code === 200) {
          let currentAddr = {}
          let consignee_id = 0
          this.setData({
            addressList: data
          })
          if (app.globalData.chooseAddress) {
            consignee_id = app.globalData.chooseAddress.id
            currentAddr = app.globalData.chooseAddress
            delete app.globalData.chooseAddress
          } else if (data.length) {
            data.forEach(item => {
              if (item.is_default === 0) {
                currentAddr = item
              }
            })
          }
          this.setData({
            addressList: data,
            submitForm: {
              ...this.data.submitForm,
              consignee_id
            },
            currentAddr
          })
        }
      }
    })
  },
  onShow() {
    this.getAddress()
  },
  onLoad () {
    this.getDetails()
  },
})
